package com.google.sydym6.controllers;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;

import com.google.sydym6.logic.IRadioScrobblerModel;
import com.google.sydym6.logic.RadioScrobblerModel;
import com.google.sydym6.logic.exceptions.LastfmLoginException;
import com.google.sydym6.logic.utils.Constants;
import com.google.sydym6.view.activities.LoginActivity;
import com.google.sydym6.view.activities.SettingsActivity;
import com.google.sydym6.view.fragments.LastfmLoginDialogFragment;
import com.perm.kate.api.Api;

public class SettingsController implements ISettingsController {

	private static final int REQUEST_VK_LOGIN = 1;
	private IRadioScrobblerModel model;
	private SettingsActivity view;

	public SettingsController(SettingsActivity view) {
		this.view = view;
		this.model = RadioScrobblerModel.getInstance();
	}

	@Override
	public boolean hasVkAccount() {
		return model.getVkApi() != null;
	}

	@Override
	public void changeVk() {
		if (model.getVkApi() == null) {
			view.vkSignInOutButton.setEnabled(false);
			Intent intent = new Intent();
			intent.setClass(view, LoginActivity.class);
			view.startActivityForResult(intent, REQUEST_VK_LOGIN);
		} else {
			model.setVkApi(null, 0, null);
			view.changeVkButton();
		}
	}

	@Override
	public boolean hasLastfmAccount() {
		return model.getScrobbler().hasLastFmAccount();
	}

	@Override
	public void changeLastfmAccount(FragmentManager fm, String tag) {
		if (hasLastfmAccount()) {
			try {
				model.setLastFmAccount(null, null);
			} catch (LastfmLoginException e) {
			} finally {
				view.changeLastfmButton();
			}
		} else {
			view.lastfmSignInOutButton.setEnabled(false);
			DialogFragment lastfmDialog = new LastfmLoginDialogFragment();
			lastfmDialog.show(fm, tag);
		}
	}

	@Override
	public void checkOnActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_VK_LOGIN) {
			if (resultCode == Activity.RESULT_OK) {
				model.setVkApi(data.getStringExtra("token"), 
						       data.getLongExtra("user_id", 0),
						       new Api(data.getStringExtra("token"), Constants.API_ID));
				view.changeVkButton();
				return;
			}
		}

		model.setVkApi(null, 0, null);
		view.changeVkButton();
	}
}
